package com.payment.web.controller.app.merchant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.payment.common.base.AjaxResult;
import com.payment.common.base.Const;
import com.payment.common.constant.Constants;
import com.payment.common.type.MerchantImgStatus;
import com.payment.common.utils.Md5Utils;
import com.payment.common.utils.RedisPoolUtil;
import com.payment.common.utils.StringUtils;
import com.payment.common.utils.aliyun.OSSClientUtil;
import com.payment.common.utils.file.FileUtils;
import com.payment.system.domain.IssBank;
import com.payment.system.domain.Merchant;
import com.payment.system.domain.MerchantImage;
import com.payment.system.domain.MerchantWallet;
import com.payment.system.service.IIssBankService;
import com.payment.system.service.IMerchantImageService;
import com.payment.system.service.IMerchantIncreaseLimitService;
import com.payment.system.service.IMerchantService;
import com.payment.system.service.IMerchantWalletService;
import com.payment.system.util.GuangGuUtil;

/**
 * @author fuzhili
 * @Description: app端商户处理
 * 1.实名认证
 * @date 2019/1/21 10:28
 */
@Controller
@RequestMapping("/app/merchant/info")
public class AppMerchantController {

    private static final Logger log = LoggerFactory.getLogger(AppMerchantController.class);

    @Autowired
    private IMerchantImageService merchantImageService;
    @Autowired
    private IMerchantService merchantService;
    @Autowired
    private IIssBankService issBankService;
    @Autowired
    private IMerchantWalletService merchantWalletService;
    @Autowired
    private IMerchantIncreaseLimitService limitService;

    /**
     * app商户实名认证第一步，保存身份证信息
     *
     * @param fileImg    身份证图
     * @param merchantId 商户ID
     * @return
     */
    @PostMapping("/authenticationOne")
    @ResponseBody
    public AjaxResult authenticationOne(MultipartFile[] fileImg, String merchantId) {
        if (fileImg == null || fileImg.length < 1) {
            return AjaxResult.error(1, "认证失败：请上传身份证照片！");
        }
        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "认证失败：获取商户信息失败！");
        }
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        try {
            String imgType = MerchantImgStatus.E.getCode();
            for (int i = 0; i < fileImg.length; i++) {
                if (i == 1) {
                    imgType = MerchantImgStatus.F.getCode();
                }
                if (!FileUtils.fileType(fileImg[i])) {
                    return AjaxResult.error(1, "图片类型错误");
                }
                String imgUrl = OSSClientUtil.uploadImg2Oss(fileImg[i], Constants.MERCHANT_CARD + merchant.getPhone() + "/");
                merchantImageService.insertMerchantImageByMerchantId(imgUrl, merchantId, imgType);
            }
            return AjaxResult.success("图片上传成功，等候审核！");
        } catch (Exception e) {
            log.error("实名认证图片上传失败", e);
            return AjaxResult.error("实名认证图片上传失败!请联系客服咨询");
        }
    }


    /**
     * app商户补全手持身份证信息 对比照片 第二步
     *
     * @param fileImg
     * @return
     */
    @PostMapping("/authenticationVt")
    @ResponseBody
    public AjaxResult authenticationVt(MultipartFile[] fileImg, String merchantId) {
        if (fileImg == null) {
            return AjaxResult.error(1, "认证失败：请上传手持身份证照正面！");
        }
        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "认证失败：获取商户信息失败！");
        }
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (StringUtils.isNull(merchant)) {
            return AjaxResult.error(1, "认证失败：获取商户信息失败！");
        }
        List<MerchantImage> imageList = merchantImageService.selectMerchantImageListByMerchantIdAndTypeTWO(merchantId, MerchantImgStatus.E.getCode());
        if (StringUtils.isEmpty(imageList)) {
            //code 判断为 6  让客户去补全信息 第一步身份证正反面
            return AjaxResult.error(6, "请上传身份证人像面,如有疑问请联系客服咨询");
        }
        try {
            String imgType = MerchantImgStatus.M.getCode();
            if (!FileUtils.fileType(fileImg[0])) {
                return AjaxResult.error(1, "图片类型错误,如有疑问请联系客服咨询");
            }
            String imgUrlM = OSSClientUtil.uploadImg2Oss(fileImg[0], Constants.MERCHANT_CARD + merchant.getPhone() + "/");
            merchantImageService.insertMerchantImageByMerchantId(imgUrlM, merchantId, imgType);
//            String imgUrlE = imageList.get(0).getImageUrl();
//            if (!imgUrlE.contains("http")) {
//                imgUrlE = OSSClientUtil.getImgUrl(imgUrlE);
//            }
            return AjaxResult.success("认证成功！");
//            return merchantService.authenticationVt(imgUrlM, imgUrlE, merchant);
        } catch (Exception e) {
            log.error("app实名认证失败:{}", e);
            return AjaxResult.error("认证失败！如有疑问请联系客服咨询");
        }
    }

    /**
     * app商户实名认证 身份检测   APP活体检测后调用
     *
     * @param fileImg
     * @param merchantId
     * @param name
     * @param idCard
     * @return
     */
    @PostMapping("/personVerify")
    @ResponseBody
    public AjaxResult personVerify(MultipartFile fileImg, String merchantId, String name, String idCard) {
        if (fileImg == null) {
            return AjaxResult.error(1, "认证失败：请上传身份证照片！");
        }
        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "认证失败：获取商户信息失败！");
        }
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        try {
            if (!FileUtils.fileType(fileImg)) {
                return AjaxResult.error(1, "图片类型错误");
            }
            String imgUrl = OSSClientUtil.uploadImg2Oss(fileImg, Constants.MERCHANT_CARD + merchant.getPhone() + "/");
            merchantImageService.insertMerchantImageByMerchantId(imgUrl, merchantId, MerchantImgStatus.S.getCode());
            return merchantService.personVerify(imgUrl, merchantId, name, idCard);
        } catch (Exception e) {
            log.error("实名认证图片上传失败", e);
            return AjaxResult.error("实名认证图片上传失败!请联系客服咨询");
        }

    }

    /**
     * app商户实名认证第二步，实名认证四要素审核
     *
     * @param merchantId   用户ID
     * @param name         姓名
     * @param idCard       身份证号
     * @param phone        手机号
     * @param bankAccount  储蓄卡号
     * @param bankProvince 开户行省
     * @param bankCity     开户行市
     * @return
     */
    @PostMapping("/authenticationTwo")
    @ResponseBody
    public AjaxResult authenticationTwo(String merchantId, String name,
                                        String idCard, String phone, String bankAccount, String bankProvince, String bankCity) {
        return merchantService.authenticationTwo(merchantId, name,
                idCard, phone, bankAccount, bankProvince, bankCity);
    }



    /**
     * 获取用户基本信息，切换上下级用户
     *
     * @param merchantId
     * @return
     */
    @RequestMapping("/details")
    @ResponseBody
    public AjaxResult details(String merchantId,
                              @RequestParam(defaultValue = "0") Integer authorizationParent) {
        if (StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "缺失参数");
        }
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (merchant == null) {
            return AjaxResult.error(2, "该用户不存在");
        }
        if (authorizationParent == 1 && merchant.getAuthorizationParent().equals(0)) {
            return AjaxResult.error(3, "该用户为授权上级登录");
        }
        MerchantWallet mw = merchantWalletService.selectMerchantWalletByMerchantId(merchantId);
        List<MerchantImage> imageList = merchantImageService.selectMerchantImageListByMerchantIdAndType(merchantId,
                MerchantImgStatus.HI.getCode());
        // 用户基本信息
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("authorizationParent", merchant.getAuthorizationParent());
        map.put("isOneself", authorizationParent);
        map.put("totalMoney", mw.getTotalMoney());
        map.put("balanceMoney", mw.getBalanceMoney());
        map.put("integral", mw.getCashIntegral());
        map.put("merchantCnName", merchant.getMerchantCnName());
        map.put("phone", merchant.getPhone());
        map.put("linkPhone", merchant.getReservePhone());
        map.put("level", merchant.getLevel());
        map.put("payPwd", merchant.getPaymentPwd() == null ? "" : merchant.getPaymentPwd());
        map.put("freezeStatus", merchant.getRealNameStatus());
        map.put("bankAccount", merchant.getBankAccount() != null ? merchant.getBankAccount() : "");
        map.put("idCardNumber", merchant.getIdCardNumber());
        map.put("createTime", merchant.getCreateTime());
        if (imageList != null && imageList.size() > 0) {
            map.put("imageHead", imageList.get(0).getImageUrl());
        } else {
            map.put("imageHead", "");
        }
        IssBank issBank = issBankService.selectIssBankByCode(merchant.getBankCode());
        String bankName = "";
        String bankBackgroundImg = "";
        String bankLogoImg = "";
        String depositCardImg = "";
        // 银行卡信息
        if (issBank != null) {
            bankName = issBank.getShortCnName();
            bankBackgroundImg = issBank.getBankBackgroundImg();
            bankLogoImg = issBank.getBankLogoImg();
            depositCardImg = issBank.getDepositCardImg();
        }
        map.put("bankName", bankName);
        map.put("bankBackgroundImg", bankBackgroundImg); // 银行卡背景图片
        map.put("bankLogoImg", bankLogoImg);// 银行卡logo图片
        map.put("depositCardImg", depositCardImg);// 银行卡logo图片
        map.put("pwd", "123456");// 环信密码
        map.put("userStatus", merchant.getUserStatus()); //是否禁用
        return AjaxResult.successAndData("获取用户信息成功", map);
    }


    /**
     * 更换储蓄卡
     *
     * @param merchantId  商户id
     * @param bankAccount 储蓄卡号
     * @param linkPhone   预留手机号
     * @param payPwd      交易密码
     * @return
     * @throws Exception
     */
    @RequestMapping("/replaceSettlementCard")
    @ResponseBody
    public AjaxResult replaceSettlementCard(String merchantId, String bankAccount, String linkPhone, String payPwd, String bankProvince, String bankCity) throws Exception {
        return merchantService.replaceSettlementCard(merchantId, bankAccount, linkPhone, payPwd, bankProvince, bankCity);

    }

    /**
     * 验证支付密码
     *
     * @param PaymentPassword 密码
     * @param merchantId      商户id
     * @return
     */
    @RequestMapping("/verifyPaymentPassword")
    @ResponseBody
    public AjaxResult verifyPaymentPassword(String PaymentPassword, String merchantId) {
        if (StringUtils.isEmpty(PaymentPassword) || StringUtils.isEmpty(merchantId)) {
            return AjaxResult.error(1, "缺少必要参数");
        }
        Merchant m = merchantService.selectMerchantById(merchantId);
        if (m == null) {
            return AjaxResult.error(2, "用户信息有误");
        }
        if (StringUtils.isEmpty(m.getPaymentPwd())) {
            return AjaxResult.error(3, "未设置支付密码，设置支付密码");
        }
        if (Md5Utils.encrypt2MD5(PaymentPassword).equals(m.getPaymentPwd())) {
            return AjaxResult.success("验证通过");
        } else {
            return AjaxResult.error(4, "密码输入错误，请重新输入");
        }
    }


    /**
     * 更换储蓄卡预留手机号
     *
     * @param merchantId 商户id
     * @param linkPhone  手机号
     * @param code       手机验证码
     * @param password   登錄密碼
     * @return
     * @throws Exception
     */
    @RequestMapping("/replaceLinkPhone")
    @ResponseBody
    public AjaxResult replaceLinkPhone(String merchantId, String linkPhone, String code, String password) throws Exception {
        if (StringUtils.isEmpty(merchantId) || StringUtils.isEmpty(linkPhone) || StringUtils.isEmpty(password)) {
            return AjaxResult.error(1, "缺少必要参数");
        }
        if (code != null) {
            String redisCode = RedisPoolUtil.get(linkPhone + Const.TIME);
            if (redisCode == null || "".equals(redisCode)) {
                return AjaxResult.error(2, "请输入手机验证码");
            }
            if (!redisCode.equals(code)) {
                return AjaxResult.error(3, "验证码输入错误");
            }
        }
        //根据ID查询用户信息
        Merchant merchant = merchantService.selectMerchantById(merchantId);
        if (Md5Utils.encrypt2MD5(password).equals(merchant.getPassword())) {
            //预留手机号
            merchant.setReservePhone(linkPhone);
            //请求流水号
            merchant.setSeriaNo(StringUtils.createNum());
            JSONObject json = GuangGuUtil.VerificationOfFourElements(merchant);
            if (StringUtils.isNotNull(json)) {
                if ("SUCCESS".equals(json.getString("ret_code"))) {
                    if ("YQB000000".equals(json.getString("res_code"))) {
                        merchantService.updateMerchant(merchant);
                        RedisPoolUtil.del(linkPhone + Const.TIME);
                        return AjaxResult.success("修改成功");
                    } else {
                        return AjaxResult.error(json.getString("res_msg"));
                    }
                }
            }
        } else {
            return AjaxResult.error(4, "密码输入错误，请重新输入");
        }
        return AjaxResult.error("四要素鉴权失败，请联系客服咨询");
    }

    /**
     * 会员界面
     *
     * @param merchantId 商户id
     * @return
     * @throws Exception
     */
    @RequestMapping("/vipPage")
    @ResponseBody
    public AjaxResult vipPage(String merchantId) throws Exception {
        return merchantService.vipPage(merchantId);

    }


    /**
     * 授权设置
     *
     * @param merchantId 商户id
     * @return
     * @throws Exception
     */
    @RequestMapping("/authorizationParent")
    @ResponseBody
    public AjaxResult authorizationParent(String merchantId, Integer authorizationParent) throws Exception {
        Merchant mer = new Merchant();
        mer.setId(merchantId);
        mer.setAuthorizationParent(authorizationParent);
        merchantService.updateMerchant(mer);
        return AjaxResult.success();
    }

    /**
     * 下级列表授权设置
     *
     * @param phone 商户手机号
     * @return
     * @throws Exception
     */
    @RequestMapping("/authorizationList")
    @ResponseBody
    public AjaxResult authorizationParent(String phone) {
        Merchant merchant = new Merchant();
        merchant.setParentPhone(phone);
        List<Merchant> merchantList = merchantService.selectMerchantList(merchant);
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (Merchant merchant2 : merchantList) {
            Map<String, Object> map = new HashMap<>();
            long count = limitService.selectCountByMerchantId(merchant2.getId());
            map.put("count", count);
            map.put("merchantId", merchant2.getId());
            map.put("authorizationParent", merchant2.getAuthorizationParent());
            map.put("merchantName", merchant2.getMerchantCnName());
            map.put("merchantPhone", merchant2.getReservePhone());
            mapList.add(map);
        }
        return AjaxResult.successAndData("成功", mapList);
    }
}
